<script setup>
import ip from '@/utils/baseURL.js';
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { ArrowUp, ArrowDown, Delete, EditPen } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 获取当前用户的 session
const session = localStorage.getItem('session');

// 轮播图列表数据
const carouselList = ref([]);

// 修改上传URL
const uploadUrl = `${ip}/inter/upload`;

// 请求头
const headers = {
  'Session': localStorage.getItem('session') || ''
};

// 抽屉相关数据
const drawer = ref({
  visible: false,
  currentId: null,
  currentImage: '',
  newImage: ''
});

// 打开编辑抽屉
const openEditDrawer = (carousel) => {
  drawer.value = {
    visible: true,
    currentId: carousel.id,
    currentImage: carousel.image,
    newImage: ''
  };
};

// 抽屉内上传成功处理
const handleDrawerUploadSuccess = (response, file) => {
  if (response.code === 200) {
    drawer.value.newImage = response.data; // 仅更新预览图
    ElMessage.success('新图片上传成功，请确认修改');
  } else {
    ElMessage.error(response.message || '上传失败');
  }
};
// 在关闭抽屉的方法中
const closeDrawer = () => {
  drawer.value = {
    visible: false,
    currentId: null,
    currentImage: '',
    newImage: ''
  };
};

// 更新轮播图图片
const updateCarouselImage = async () => {
  if (!drawer.value.currentId) {
    ElMessage.warning('缺少轮播图ID');
    return;
  }
  
  if (!drawer.value.newImage) {
    ElMessage.warning('请先上传新图片');
    return;
  }

  try {
    console.log('准备更新轮播图:', drawer.value.currentId, drawer.value.newImage);
    
    const response = await axios.post(`${ip}/inter/carousel/update`, 
      {
        id: drawer.value.currentId,
        image: drawer.value.newImage
      }, 
      { headers }
    );

    if (response.data.code === 200) {
      ElMessage.success('修改成功');
      // 只调用一次closeDrawer即可
      closeDrawer();
      // 添加延迟确保状态先重置再获取数据
      setTimeout(async () => {
        await fetchCarouselList(); // 刷新列表
      }, 100);
      // 全页面刷新（简单粗暴）
      setTimeout(() => {
        location.reload(); // 强制刷新页面
      }, 1000); // 1秒后刷新让用户看到提示
    } else {
      ElMessage.error(response.data.message || '修改失败');
    }
  } catch (error) {
    console.error('修改失败:', error);
    ElMessage.error(error.response?.data?.message || '网络错误');
  }
};

// 获取轮播图列表
const fetchCarouselList = async () => {
  try {
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    const response = await axios.post(`${ip}/inter/carousel/get?t=${timestamp}`, {});
    
    console.log('获取到的轮播图列表:', response.data.data?.length || 0, '条记录');
    
    if (response.data.code === 200) {
      carouselList.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取轮播图列表失败');
    }
  } catch (error) {
    console.error('获取轮播图失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过10MB!');
    return false;
  }
  
  return true;
};

// 上传成功处理
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    // 获取上传后的图片URL
    const imageUrl = response.data; // 阿里云OSS返回的URL
    
    // 创建新的轮播图
    addNewCarousel(imageUrl);
    
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.message || '上传失败');
  }
};

// 上传失败处理
const handleUploadError = () => {
  ElMessage.error('上传失败，请稍后重试');
};

// 添加新轮播图到系统
const addNewCarousel = async (imageUrl) => {
  try {
    // 构造新轮播图数据
    const newCarousel = {
      image: imageUrl
      // id会由后端生成
    };
    
    // 调用更新接口添加新轮播图
    const response = await axios.post(`${ip}/inter/carousel/update`, newCarousel, {
      headers
    });
    
    if (response.data.code === 200) {
      ElMessage.success('轮播图添加成功');
      fetchCarouselList(); // 重新获取列表
    } else {
      ElMessage.error(response.data.message || '添加轮播图失败');
    }
  } catch (error) {
    console.error('添加轮播图失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 修改上移轮播图方法，使用update接口
const moveUp = async (index) => {
  if (index <= 0) return;
  
  try {
    // 交换两个轮播图的位置
    const temp = {...carouselList.value[index]};
    const target = {...carouselList.value[index - 1]};
    
    // 先更新当前项
    await updateCarousel(temp.id, target.image);
    // 再更新目标项
    await updateCarousel(target.id, temp.image);
    
    ElMessage.success('排序已更新');
    fetchCarouselList(); // 重新获取列表
  } catch (error) {
    console.error('排序失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 修改下移轮播图方法，使用update接口
const moveDown = async (index) => {
  if (index >= carouselList.value.length - 1) return;
  
  try {
    // 交换两个轮播图的位置
    const temp = {...carouselList.value[index]};
    const target = {...carouselList.value[index + 1]};
    
    // 先更新当前项
    await updateCarousel(temp.id, target.image);
    // 再更新目标项
    await updateCarousel(target.id, temp.image);
    
    ElMessage.success('排序已更新');
    fetchCarouselList(); // 重新获取列表
  } catch (error) {
    console.error('排序失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 更新轮播图通用方法
const updateCarousel = async (id, imageUrl) => {
  try {
    const response = await axios.post(`${ip}/inter/carousel/update`, {
      id: id,
      image: imageUrl
    }, { headers });
    
    if (response.data.code !== 200) {
      throw new Error(response.data.message || '更新失败');
    }
    
    return response.data;
  } catch (error) {
    console.error('更新轮播图失败:', error);
    throw error;
  }
};

// 删除轮播图
const deleteCarousel = async (id, index) => {
  try {
    await ElMessageBox.confirm('确定要删除这张轮播图吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    // 使用update接口，将image设为空字符串可能意味着删除
    // 或者根据实际需求调整此处逻辑
    const response = await axios.post(`${ip}/inter/carousel/update`, {
      id: id,
      image: '' // 假设空字符串表示删除，或者使用其他标记方式
    }, { headers });
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      carouselList.value.splice(index, 1);
      // 重新获取列表确保数据一致
      fetchCarouselList();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }
};

// 添加键盘状态
const keyStatus = ref({
  shift: false,
  d: false,
  f: false,
  w: false
});

// 添加键盘按下事件处理
const handleKeyDown = (event) => {
  // 根据按键更新状态
  if (event.key === 'Shift') keyStatus.value.shift = true;
  else if (event.key.toLowerCase() === 'd') keyStatus.value.d = true;
  else if (event.key.toLowerCase() === 'f') keyStatus.value.f = true;
  else if (event.key.toLowerCase() === 'w') keyStatus.value.w = true;

  // 检查是否所有目标键都已按下
  if (keyStatus.value.shift && keyStatus.value.d && 
      keyStatus.value.f && keyStatus.value.w) {
    // 跳转到目标页面
    router.push('/admin/DFWPage');
    // 重置键盘状态，防止连续触发
    resetKeyStatus();
  }
};

// 添加键盘释放事件处理
const handleKeyUp = (event) => {
  // 根据按键更新状态
  if (event.key === 'Shift') keyStatus.value.shift = false;
  else if (event.key.toLowerCase() === 'd') keyStatus.value.d = false;
  else if (event.key.toLowerCase() === 'f') keyStatus.value.f = false;
  else if (event.key.toLowerCase() === 'w') keyStatus.value.w = false;
};

// 添加重置键盘状态的函数
const resetKeyStatus = () => {
  keyStatus.value = {
    shift: false,
    d: false,
    f: false,
    w: false
  };
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCarouselList();
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown);
  window.addEventListener('keyup', handleKeyUp);
});

// 添加 onUnmounted 钩子移除事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
  window.removeEventListener('keyup', handleKeyUp);
});
</script>

<template>
  <div class="carousel-manager">
    <h2>轮播图管理</h2>
    
    <div class="upload-section">
      <el-upload
        class="carousel-uploader"
        :action="uploadUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        accept="image/*"
        :limit="1"
        :show-file-list="false"
        name="image"
      >
        
        
      </el-upload>
    </div>
    
    <div class="carousel-list">
      <el-table :data="carouselList" style="width: 100%" border>
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        
        <el-table-column label="预览图" width="300">
          <template #default="scope">
            <div class="image-preview">
              <el-image 
                :src="scope.row.image" 
                fit="contain"
                :preview-src-list="[scope.row.image]"
                preview-teleported
              ></el-image>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="图片链接" min-width="300">
          <template #default="scope">
            <div class="image-url">{{ scope.row.image }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.$index !== 0" 
              type="primary" 
              size="small" 
              circle
              @click="moveUp(scope.$index)"
            >
              <el-icon><ArrowUp /></el-icon>
            </el-button>
            
            <el-button 
              v-if="scope.$index !== carouselList.length - 1" 
              type="primary" 
              size="small" 
              circle
              @click="moveDown(scope.$index)"
            >
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            
            <el-button 
              type="warning" 
              size="small" 
              circle
              @click="openEditDrawer(scope.row)"
            >
              <el-icon><EditPen /></el-icon>
            </el-button>
            
            <el-button 
              type="danger" 
              size="small" 
              circle
              @click="deleteCarousel(scope.row.id, scope.$index)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <el-drawer
      v-model="drawer.visible"
      title="修改轮播图"
      direction="rtl"
      size="400px"
      :before-close="closeDrawer"
    >
    
      <div class="drawer-content">
        <div class="current-image">
          <h4>当前图片</h4>
          <el-image 
            v-if="drawer.currentImage" 
            :src="drawer.currentImage" 
            fit="contain"
            class="image-preview-large"
          ></el-image>
          <p class="image-url">{{ drawer.currentImage }}</p>
        </div>
       
        <div class="upload-new-image">
          <h4>上传新图片</h4>
          <el-upload
            class="drawer-uploader"
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleDrawerUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
            :limit="1"
            :show-file-list="false"
            name="image"
          >
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                建议尺寸: 1600×500像素，JPG/PNG格式，文件大小不超过10MB
              </div>
            </template>
          </el-upload>
          
          <div v-if="drawer.newImage" class="new-image-preview">
            <el-image 
              :src="drawer.newImage" 
              fit="contain"
              class="image-preview-large"
            ></el-image>
            <p class="image-url">{{ drawer.newImage }}</p>
          </div>
        </div>
        
        <div class="drawer-footer">
          <el-button @click="closeDrawer">取消</el-button>
          <el-button 
            type="primary" 
            @click="updateCarouselImage" 
            :disabled="!drawer.newImage || !drawer.currentId"
          >
            确认修改
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>



<style lang="scss" scoped>
.carousel-manager {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    color: #333;
  }

  .upload-section {
    margin-bottom: 30px;
    
    .carousel-uploader {
      margin-bottom: 10px;
    }
  }

  .carousel-list {
    .image-preview {
      width: 280px;
      height: 100px;
      overflow: hidden;
      
      .el-image {
        width: 100%;
        height: 100%;
      }
    }
    
    .image-url {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 12px;
      color: #666;
    }
  }
  
  .drawer-content {
    padding: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
      color: #333;
    }
    
    .current-image, .upload-new-image {
      margin-bottom: 30px;
    }
    
    .image-preview-large {
      width: 100%;
      height: 180px;
      margin-bottom: 10px;
      border: 1px solid #eee;
      border-radius: 4px;
    }
    
    .new-image-preview {
      margin-top: 15px;
    }
    
    .drawer-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px;
      background: white;
      border-top: 1px solid #eee;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>